package com.aaa.controller;

import com.aaa.entity.Userinfo;
import com.aaa.service.UserInfoService;
import com.sun.tools.javac.util.Convert;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/6/20 9:25
 * @description：
 * @modified By：
 * @version:
 */
@WebServlet(urlPatterns = "/userinfo")
public class UserInfoController  extends HttpServlet {


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //将所有的参数存入一个map集合中
        Map<String,Object> map = new HashMap();
        //获取所有的参数名集合
        Enumeration<String> parameterNames = req.getParameterNames();
        //遍历所有的参数名
        while (parameterNames.hasMoreElements()){
            /* System.out.println(parameterNames.nextElement());*/
            //获取第一个参数名
            String key=parameterNames.nextElement();
            //根据参数名获取参数值
            Object value=req.getParameter(key);
            //将参数名和参数值存入map集合中
            map.put(key,value);
        }
        //所有的servlet都有一个方法，getServletContext，servletContext是applicationScope
        ServletContext servletContext = getServletContext();
        ApplicationContext applicationContext = (ApplicationContext) servletContext.getAttribute("applicationContext");
        //获取service的bean
        UserInfoService userInfoService= applicationContext.getBean("userInfoServiceImpl",UserInfoService.class);
        switch (map.get("method")+""){
            case "select":

                List<Userinfo> userinfoList = userInfoService.findAllUser();
                req.getSession().setAttribute("userinfoList",userinfoList);
                req.getRequestDispatcher("showUser.jsp").forward(req,resp);
                break;
            case "delete":
                userInfoService.deleteUserInfoById(Integer.parseInt(map.get("userid").toString()));
                userinfoList = userInfoService.findAllUser();
                req.getSession().setAttribute("userinfoList",userinfoList);
                req.getRequestDispatcher("showUser.jsp").forward(req,resp);
                break;
            default:
                System.out.println("不支持的方法");
                break;
        }
    }
}
